package com.szp.drug.component.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.szp.drug.component.mapper.DrugInstrumentMapper;
import com.szp.drug.component.mapper.DrugMedicineMapper;
import com.szp.drug.component.mapper.DrugSellMapper;
import com.szp.drug.entity.DrugInstrument;
import com.szp.drug.entity.DrugMedicine;
import com.szp.drug.entity.DrugSell;
import com.szp.drug.entity.DrugSellPage;
import com.szp.drug.util.DrugConstant;
import com.szp.drug.util.ResultEntity;
import com.szp.drug.component.service.api.DrugSellService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 售出记录实现类
 * @author SuZePing
 * @create 2021-03-06 14:00
 * @E-mail suzeping10@126.com
 */
@Slf4j
@Service
public class DrugSellServiceImpl extends ServiceImpl<DrugSellMapper, DrugSell> implements DrugSellService {

	@Autowired
	private DrugSellMapper sellMapper;

	@Autowired
	private DrugMedicineMapper medicineMapper;

	@Autowired
	private DrugInstrumentMapper instrumentMapper;

	/**
	 * 获取全部在售药品及器械
	 * @return
	 */
	@Override
	public ResultEntity<List<Map<String, Object>>> getAllOther() {
		List<Map<String, Object>> resultList = new ArrayList<>();
		// 获取未删除的药品且数量大于0
		QueryWrapper<DrugMedicine> medicineWrapper = new QueryWrapper<>();
		medicineWrapper.eq("deleted","0")
				.gt("medicine_total","0");
		List<DrugMedicine> selMedicineList = medicineMapper.selectList(medicineWrapper);
		for (DrugMedicine drugMedicine : selMedicineList) {
			Map<String, Object> medicine = MapUtil.newHashMap();
			medicine.put("otherId",drugMedicine.getMedicineId());
			medicine.put("otherName",drugMedicine.getMedicineName() + " [药品]");
			resultList.add(medicine);
		}
		// 获取未删除的器械且数量大于0
		QueryWrapper<DrugInstrument> instrumentWrapper = new QueryWrapper<>();
		instrumentWrapper.eq("deleted","0")
				.gt("instrument_total","0");
		List<DrugInstrument> selInstrumentList = instrumentMapper.selectList(instrumentWrapper);
		for (DrugInstrument drugInstrument : selInstrumentList) {
			Map<String, Object> instrument = MapUtil.newHashMap();
			instrument.put("otherId",drugInstrument.getInstrumentId());
			instrument.put("otherName",drugInstrument.getInstrumentName() + " [器械]");
			resultList.add(instrument);
		}
		return ResultEntity.success(resultList);
	}

	/**
	 * 获取药品或器械的单价
	 * @param otherId
	 * @return
	 */
	@Override
	public ResultEntity<String> getOtherPrice(String otherId) {
		if (StrUtil.hasEmpty(otherId)){
			return ResultEntity.error("主键id不能为空!");
		}
		// 药品
		if (otherId.startsWith("ME")){
			DrugMedicine selMedicine = medicineMapper.selectById(otherId);
			String medicinePrice = selMedicine.getMedicinePrice();
			return ResultEntity.success(medicinePrice);
		}
		// 器械
		if (otherId.startsWith("IN")){
			DrugInstrument selInstrument = instrumentMapper.selectById(otherId);
			String instrumentPrice = selInstrument.getInstrumentPrice();
			return ResultEntity.success(instrumentPrice);
		}
		return ResultEntity.error("需要填入药品id或器械id!");
	}

	/**
	 * 分页获取售出记录
	 * @param sellName
	 * @param otherName
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public ResultEntity<PageInfo<DrugSellPage>> getPageInfo(String sellName, String otherName, String pageNum, String pageSize) {
		// 根据搜索条件中的otherName搜索药品
		QueryWrapper<DrugMedicine> medicineWrapper = new QueryWrapper<>();
		medicineWrapper.eq("deleted","0")
				.like("medicine_name",otherName);
		List<DrugMedicine> selMedicineList = medicineMapper.selectList(medicineWrapper);
		// 根据otherName得到药品中的medicineId
		List<String> selMedicineIdList = selMedicineList.stream()
				.map(DrugMedicine::getMedicineId)
				.collect(Collectors.toList());
		// 根据搜索条件中的otherName搜索器械
		QueryWrapper<DrugInstrument> instrumentWrapper = new QueryWrapper<>();
		instrumentWrapper.eq("deleted","0")
				.like("instrument_name",otherName);
		List<DrugInstrument> selInstrumentList = instrumentMapper.selectList(instrumentWrapper);
		// 根据otherName得到器械中的instrumentId
		List<String> selInstrumentIdList = selInstrumentList.stream()
				.map(DrugInstrument::getInstrumentId)
				.collect(Collectors.toList());
		// 把查询到的药品或器械的id放入新的otherIdList中
		List<String> selOtherIdList = CollUtil.newArrayList();
		selOtherIdList.addAll(selMedicineIdList);
		selOtherIdList.addAll(selInstrumentIdList);
		QueryWrapper<DrugSell> sellWrapper = new QueryWrapper<>();
		if (ArrayUtil.hasEmpty(selOtherIdList)){
			// 没查询到药品或器械
			return ResultEntity.success(null);
		}else {
			// 使用id去drug_sell表中查询
			sellWrapper.eq("deleted","0")
					.and(m -> m.like("sell_name",sellName).in("other_id",selOtherIdList))
					.orderByAsc("sell_time");
		}
		List<DrugSell> selSellList = sellMapper.selectList(sellWrapper);
		List<DrugSellPage> resultList = new ArrayList<>();
		for (DrugSell sell : selSellList) {
			DrugSellPage sellPage = new DrugSellPage();
			String otherId = sell.getOtherId();
			if (otherId.startsWith("ME")){
				String medicineName = medicineMapper.selectById(otherId).getMedicineName();
				sellPage.setOtherName(medicineName);
			}else if (otherId.startsWith("IN")){
				String instrumentName = instrumentMapper.selectById(otherId).getInstrumentName();
				sellPage.setOtherName(instrumentName);
			}else {
				return ResultEntity.error(DrugConstant.MESSAGE_SYSTEM_ERROR_DATAERROR);
			}
			sellPage.setSellId(sell.getSellId())
					.setSellName(sell.getSellName())
					.setSellTotal(sell.getSellTotal())
					.setOtherId(sell.getOtherId())
					.setSellMoney(sell.getSellMoney())
					.setSellTime(sell.getSellTime());
			resultList.add(sellPage);
		}
		PageInfo<DrugSellPage> pageInfo = getPageInfo(resultList, pageNum, pageSize);
		return ResultEntity.success(pageInfo);
	}

	/**
	 * 售出记录
	 * @param sell
	 * @return
	 */
	@Override
	public ResultEntity<Map<String,Object>> saveSell(DrugSell sell) {
		Map<String, Object> resultMap = CollUtil.newHashMap();
		String otherId = sell.getOtherId();
		if (StrUtil.hasEmpty(otherId)){
			return ResultEntity.error("需要填写购买产品!");
		}
		// 购买数量
		int sellTotal = Integer.parseInt(sell.getSellTotal());
		// 出售的是药品
		if (otherId.startsWith("ME")){
			DrugMedicine sellMedicine = medicineMapper.selectById(otherId);
			int medicineTotal = Integer.parseInt(sellMedicine.getMedicineTotal());
			String medicineName = sellMedicine.getMedicineName();
			if (medicineTotal < sellTotal){
				return ResultEntity.error("库存不足，[" + medicineName + "]剩余" + medicineTotal + "件");
			}
			// 更新药品数量 [现有数量 - 购买数量]
			int total = medicineTotal - sellTotal;
			DrugMedicine updateMedicine = new DrugMedicine();
			updateMedicine.setMedicineId(otherId)
					.setMedicineTotal(StrUtil.toString(total));
			medicineMapper.updateById(updateMedicine);
			// 回显药品名及药品剩余数量
			resultMap.put("name",medicineName);
			resultMap.put("total",total);
		}else if (otherId.startsWith("IN")){
			DrugInstrument sellInstrument = instrumentMapper.selectById(otherId);
			int instrumentTotal = Integer.parseInt(sellInstrument.getInstrumentTotal());
			String instrumentName = sellInstrument.getInstrumentName();
			if (instrumentTotal < sellTotal){
				return ResultEntity.error("库存不足，[" + instrumentName + "]剩余" + instrumentTotal + "件");
			}
			// 更新药品数量 [现有数量 - 购买数量]
			int total = instrumentTotal - sellTotal;
			DrugInstrument updateInstrument = new DrugInstrument();
			updateInstrument.setInstrumentId(otherId)
					.setInstrumentTotal(StrUtil.toString(total));
			instrumentMapper.updateById(updateInstrument);
			// 回显器械名及器械剩余数量
			resultMap.put("name",instrumentName);
			resultMap.put("total",total);
		} else {
			return ResultEntity.error("产品信息错误!");
		}
		sell.setSellId("SE" + IdUtil.fastSimpleUUID().substring(0, 10))
				.setSellTime(DateUtil.now());
		sellMapper.insert(sell);
		// 返回新增后总数量 为数据展示页码使用
		QueryWrapper<DrugSell> sellWrapper = new QueryWrapper<>();
		sellWrapper.eq("deleted","0");
		Integer count = sellMapper.selectCount(sellWrapper);
		resultMap.put("count",count);
		return ResultEntity.success(resultMap);
	}

	/**
	 * 删除记录
	 * @param sellId
	 * @return
	 */
	@Override
	public ResultEntity<String> removeSell(String sellId) {
		if (StrUtil.hasEmpty(sellId)){
			return ResultEntity.error("主键id不能为空!");
		}
		DrugSell sell = new DrugSell();
		sell.setSellId(sellId).setDeleted("1");
		sellMapper.updateById(sell);
		return ResultEntity.success();
	}

	/**
	 * PageHelper手动对List进行分页
	 * @param resultList
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	private PageInfo<DrugSellPage> getPageInfo(List<DrugSellPage> resultList,String pageNum,String pageSize){
		int pageNumInt = Integer.parseInt(pageNum);
		int pageSizeInt = Integer.parseInt(pageSize);
		// 创建Page类
		Page<DrugSellPage> page = new Page<>(pageNumInt, pageSizeInt);
		// 为Page类中的total属性赋值
		int total = resultList.size();
		page.setTotal(total);
		// 计算当前需要显示的数据下标起始值
		int startIndex = (pageNumInt - 1) * pageSizeInt;
		int endIndex = Math.min(startIndex + pageSizeInt,total);
		// 从链表中截取需要显示的子链表，并加入到Page
		page.addAll(resultList.subList(startIndex,endIndex));
		// 以Page创建PageInfo
		return new PageInfo<>(page);
	}
}